import { redisDeserialize } from "@/api/sharing/redis";
import CodeEditor from "@/components/codemirror/CodeEditor";
import { Button, Col, message, Row, Space } from "antd";
import { forwardRef, useRef, useImperativeHandle, useMemo, useEffect } from "react";
import { openSearchPanel, gotoLine, findNext } from '@codemirror/search';

const StringEditor = ({ value, onChange, readOnly }, ref) => {
  const panelStringRef = useRef()
  const editorRef = useRef()


  useImperativeHandle(ref, () => ({
  }))

  // 格式化json
  const handleFormatJson = () => {
    try {
      if (value) {
        onChange(JSON.stringify(JSON.parse(value), null, 2))
      }
    } catch (e) {
      message.error('格式化失败')
    }
  }
  // 压缩json
  const handleCompressJson = () => {
    try {
      if (value) {
        onChange(JSON.stringify(JSON.parse(value)))
      }
    } catch (e) {
      message.error('压缩失败')
    }
  }

  const handleOpenSearch = () => {
    const editor = editorRef.current.getEditor()
    console.log(editor.editor.openSearchPanel)
    // console.log(editor.view.dispatch(openSearchPanel))
    console.log(editor)
    openSearchPanel(editor.view)
    // editor.view.execCommand(openSearchPanel);
    // editor.focus()
    // editor.setSelection({
    //   from: editor.state.doc.nodeSize,
    //   to: editor.state.doc.nodeSize
    // })
  }

  const handleGotoLine = () => {
    const editor = editorRef.current.getEditor()
    gotoLine(editor.view)
  }

  const handleGotoNextSearch = () => {
    const editor = editorRef.current.getEditor()
    findNext(editor.view)
  }

  const handleDeserialize = () => {
    redisDeserialize({
      data: value || ''
    }).then(res => {
      if (res.code == 200) {
        onChange(res.result || '')
      }
    })
  }


  // 检查是否处于全屏模式
  function isInFullScreen() {
    return !!document.fullscreenElement;
  }

  // 请求全屏
  function requestFullScreen() {
    const elem = panelStringRef.current
    if (elem.requestFullscreen) {
      elem.requestFullscreen().catch(err => {
        alert(`Error attempting to enable full-screen mode: ${err.message} (${err.name})`);
      });
    } else if (elem.webkitRequestFullscreen) { /* 旧版 Safari */
      elem.webkitRequestFullscreen();
    } else if (elem.msRequestFullscreen) { /* IE/Edge */
      elem.msRequestFullscreen();
    }
  }

  const handleFullScreen = () => {
    if (isInFullScreen()) {
      document.exitFullscreen()
    } else {
      requestFullScreen()
    }
  }
  const onKeyDown = (e) => {
    if (e.code === 'F11') { // 122 是 F11 的 keyCode
      e.preventDefault()
      handleFullScreen()
    }
  }

  useEffect(() => {
    document.addEventListener('keydown', onKeyDown);
    return () => {
      document.removeEventListener('keydown', onKeyDown)
    }
  }, [])

  return (<div ref={panelStringRef} className='panel-string-wrapper'>
    <Row style={{ flex: 0 }} className='panel-string-header-wrapper' gutter={[10, 10]}>
      <Col span={16}>
        <Space>
          <Button onClick={handleFullScreen}>F11全屏</Button>
          <Button onClick={handleOpenSearch}>Ctrl+F搜索</Button>
          <Button onClick={handleGotoNextSearch}>Ctrl+G跳转到下一个搜索目标</Button>
          <Button onClick={handleGotoLine}>Alt+G跳转到指定行</Button>
        </Space>
      </Col>
      <Col span={8}>
        <Space>
          <Button type="primary" onClick={handleFormatJson}>
            JSON格式化
          </Button>
          <Button type="primary" onClick={handleCompressJson}>
            JSON压缩
          </Button>
          {/* <Button type="primary" onClick={handleDeserialize}>反序列化</Button> */}
        </Space>
      </Col>
    </Row>
    <div className='panel-string-content'>
      <CodeEditor ref={editorRef} readOnly={readOnly} value={value || ''} height='100%' lang='json' onChange={onChange} />
    </div>
  </div>);
}

export default forwardRef(StringEditor);